/*----------------------------------------------------------------------------------------
*
*  Copyright 2019, Gao Hai Hui, <fromzeropoint@126.com>.  All rights reserved.
*  https://gitee.com/helloworldghh/xoskit.git
*  Use of this source code is governed by a MIT license
*  that can be found in the License file.
*
----------------------------------------------------------------------------------------*/
#ifndef __XOS_STL_POOL_LOCK_FREE_POOL_H__
#define __XOS_STL_POOL_LOCK_FREE_POOL_H__

#include "fake_lock.h"
#include "lock_free_queue.h"
#include <atomic>

namespace xos_stl
{

    namespace lock_free
    {
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // xos_pool

        template< class T, class Lock >
        class lock_free_pool
        {
        public:
            using INTERFACE_QUEUE = typename T::LOCK_FREE_INTERFACE_QUEUE;
            using ITEM_QUEUE = typename T::LOCK_FREE_ITEM_QUEUE;

        protected:
            xos_container::i_container* m_pContainer;
            ITEM_QUEUE queue;

        public:
            lock_free_pool() : m_pContainer( 0 ), queue()
            {
            }
            ~lock_free_pool()
            {
                term();
            }
        public:
            T* get_item()
            {
                T* pT = queue.pop_front();
                if( !pT )
                {
                    xos_stl::init_obj( pT );
                }
                return pT;
            }
            void put_item( T* pT )
            {
                queue.push_back( pT );
            }
        public:
            int init( xos_container::i_container* pContainer )
            {
                int ret = 0;
                m_pContainer = pContainer;
                queue.init( pContainer );
                return ret;
            }
            int term()
            {
                int ret = 0;
                queue.term();
                return ret;
            }

        };

    } // lock_free

} // xos_stl

#endif // __XOS_STL_POOL_LOCK_FREE_POOL_H__
